package com.example.doctor.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.example.common.entity.*;
import com.example.common.enums.ChkStatus;
import com.example.common.enums.DType;
import com.example.common.sendhttp.CaSendMessage;
import com.example.common.sendhttp.WxSendMessage;
import com.example.common.support.ApiException;
import com.example.common.support.Result;
import com.example.common.support.ResultCode;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.MapUtils;
import com.example.common.utils.RedisUtils;
import com.example.common.vo.WxSubScribeMessageVo;
import com.example.doctor.dto.req.ConfigReq;
import com.example.doctor.dto.req.PcRxListReq;
import com.example.doctor.feign.FileFeign;
import com.example.doctor.jpa.*;
import com.example.doctor.mapper.CommentMapper;
import com.example.doctor.mapper.DoctorCenterMapper;
import com.example.doctor.mapper.RxOrderMapper;
import com.example.doctor.service.DoctorCenterService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.example.doctor.utils.UserUtils;
import org.springframework.beans.factory.annotation.Value;

@Service
public class DoctorCenterServiceImpl implements DoctorCenterService {
    @Resource
    private UserUtils userUtils;
    @Resource
    private FileFeign fileFeign;

    @Resource
    ExInfoRepository exInfoRepository;

    @Resource
    DoctorBaseInfoRepository doctorBaseInfoRepository;

    @Resource
    DoctorCenterMapper doctorCenterMapper;

    @Resource
    ConfigRepository configRepository;

    @Resource
    HospitalConfigRepository hospitalConfigRepository;

    @Resource
    RxOrderMapper rxOrderMapper;

    @Resource
    CommentMapper commentMapper;

    @Resource
    CommentRepository commentRepository;

    @Resource
    private RxMainRepository rxMainRepository;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private CaSendMessage caSendMessage;

    @Resource
    private RedisUtils redisUtils;    
    @Resource
    MsgConfigRepository msgConfigRepository;
    @Resource
    private WxSendMessage wxSendMessage;
    @Resource
    private PharmacistRepository pharmacistRepository;
    @Resource
    private OrderMainRepository orderMainRepository;
    @Resource
    private PatientsInfoRepository patientsInfoRepository;
    

    @Override
    public HashMap<String, Object> MyIndex(long dcID) {
        ExInfo obj = exInfoRepository.findById(dcID).orElseThrow(() -> new ApiException(10000, "用户不存在"));
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("Service", obj.getService());
        hashMap.put("Patient", obj.getPatient());
        hashMap.put("Praise", obj.getPraise());
        hashMap.put("Prescription", obj.getPrescription());
        return hashMap;
    }

    @Override
    public HashMap<String, Object> MyInfo(long dcID) {
        DoctorBaseInfo obj = doctorBaseInfoRepository.findByDcId(dcID);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("CertificateCode", obj.getCertificateCode());
        hashMap.put("ProfessionScope", obj.getProfessionScope());
        hashMap.put("Intro", obj.getIntro());
        return hashMap;
    }

    @Override
    public Boolean MyInfoSave(DoctorBaseInfo req) {
        DoctorBaseInfo obj = doctorBaseInfoRepository.findByDcId(req.getDcId());
        obj.setCertificateCode(req.getCertificateCode());
        obj.setIntro(req.getIntro());
        try {
            doctorBaseInfoRepository.save(obj);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public Object ImgUpLoad(MultipartFile file) {
        CheckUtils.checkNull(file, new ApiException(1, "文件不能为空"));
        Result<Object> result = fileFeign.updateFile(file);
        if (result.getCode() == ResultCode.DOWNGRADE.getCode()) {
            throw new ApiException(ResultCode.DOWNGRADE.getCode(), "文件上传服务降级");
        }
        return result.getData();
    }

    @Override
    public Boolean MyHeadSave(DoctorBaseInfo req) {
        DoctorBaseInfo obj = doctorBaseInfoRepository.findByDcId(req.getDcId());
        obj.setHead(req.getHead());
        try {
            doctorBaseInfoRepository.save(obj);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> IMOrderList(int AType, int page, int limit, long UID) {
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;

        List<Map<String, Object>> list = doctorCenterMapper.IMOrderList(UID, AType, skip, limit);
        return list;
    }

    @Override
    public List<Map<String, Object>> DocATypeCount(long UID) {
        Config config = configRepository.findById(UID).orElseThrow(() -> new ApiException(10000, "用户不存在"));
        HospitalConfig hospital = hospitalConfigRepository.findByLast();
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String strNow = df.format(now);

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> date = null;
        int AType = 0;
        if (hospital.getNetConfig() && config.getNetReferral()) {
            AType = 10;
            date = doctorCenterMapper.DocATypeCount(UID, AType, strNow);
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", AType);
            ldata.put("Service", true);
            ldata.put("ToBeCount", date.get("ToBeCount"));
            ldata.put("FinCount", date.get("FinCount"));
            ldata.put("TodayAddCount", date.get("TodayAddCount"));
            ldata.put("ServiceAllCount", date.get("ServiceAllCount"));
            ldata.put("Price", config.getReferralPrice());
            ldata.put("Valid", config.getReferralValid() / 60);
            list.add(ldata);
        } else {
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", 10);
            ldata.put("Service", false);
            list.add(ldata);
        }

        if (hospital.getImgText() && config.getImgText()) {
            AType = 11;
            date = doctorCenterMapper.DocATypeCount(UID, AType, strNow);
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", AType);
            ldata.put("Service", true);
            ldata.put("ToBeCount", date.get("ToBeCount"));
            ldata.put("FinCount", date.get("FinCount"));
            ldata.put("TodayAddCount", date.get("TodayAddCount"));
            ldata.put("ServiceAllCount", date.get("ServiceAllCount"));
            ldata.put("Price", config.getImgTextPrice());
            ldata.put("Valid", config.getImgTextValid() / 60);
            list.add(ldata);
        } else {
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", 11);
            ldata.put("Service", false);
            list.add(ldata);
        }

        if (hospital.getPhone() && config.getPhone()) {
            AType = 12;
            date = doctorCenterMapper.DocATypeCount(UID, AType, strNow);
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", AType);
            ldata.put("Service", true);
            ldata.put("ToBeCount", date.get("ToBeCount"));
            ldata.put("FinCount", date.get("FinCount"));
            ldata.put("TodayAddCount", date.get("TodayAddCount"));
            ldata.put("ServiceAllCount", date.get("ServiceAllCount"));
            ldata.put("Price", config.getPhonePrice());
            ldata.put("Valid", config.getPhoneValid());
            list.add(ldata);
        } else {
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", 12);
            ldata.put("Service", false);
            list.add(ldata);
        }

        if (hospital.getVideo() && config.getVideo()) {
            AType = 13;
            date = doctorCenterMapper.DocATypeCount(UID, AType, strNow);
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", AType);
            ldata.put("Service", true);
            ldata.put("ToBeCount", date.get("ToBeCount"));
            ldata.put("FinCount", date.get("FinCount"));
            ldata.put("TodayAddCount", date.get("TodayAddCount"));
            ldata.put("ServiceAllCount", date.get("ServiceAllCount"));
            ldata.put("Price", config.getVideoPrice());
            ldata.put("Valid", config.getVideoValid());
            list.add(ldata);
        } else {
            Map<String, Object> ldata = new HashMap<>();
            ldata.put("AType", 13);
            ldata.put("Service", false);
            list.add(ldata);
        }
        return list;
    }

    @Override
    public Map<String, Object> ServiceInfo(long UID, int AType) {
        Config config = configRepository.findById(UID).orElseThrow(() -> new ApiException(10000, "用户不存在"));
        HospitalConfig hospital = hospitalConfigRepository.findByLast();
        boolean isHConfig = false;
        boolean isMustOpen = false;
        boolean isHService = false;
        Map<String, Object> info = new HashMap<>();
        switch (AType) {
            case 10:
                info.put("Service", hospital.getNetConfig() && config.getNetReferral());
                info.put("Price", config.getReferralPrice());
                info.put("Valid", config.getReferralValid() / 60);
                info.put("Reception", config.getReferralReception());
                info.put("Notice", config.getReferralService());
                isHConfig = (!hospital.getNetSelfPrice());
                isMustOpen = hospital.getNetMustOpen();
                isHService = hospital.getNetConfig();
                break;
            case 11:
                info.put("Service", hospital.getImgText() && config.getImgText());
                info.put("Price", config.getImgTextPrice());
                info.put("Valid", config.getImgTextValid() / 60);
                info.put("Reception", config.getImgTextReception());
                info.put("Notice", config.getImgTextService());
                isHConfig = (!hospital.getImgTextSelfPrice());
                isMustOpen = hospital.getImgTextMustOpen();
                isHService = hospital.getImgText();
                break;
            case 12:
                info.put("Service", hospital.getPhone() && config.getPhone());
                info.put("Price", config.getPhonePrice());
                info.put("Valid", config.getPhoneValid());
                info.put("Reception", config.getPhoneReception());
                info.put("Notice", config.getPhoneService());
                isHConfig = (!hospital.getPhoneSelfPrice());
                isMustOpen = hospital.getPhoneMustOpen();
                isHService = hospital.getPhone();
                break;
            case 13:
                info.put("Service", hospital.getVideo() && config.getVideo());
                info.put("Price", config.getVideoPrice());
                info.put("Valid", config.getVideoValid());
                info.put("Reception", config.getVideoReception());
                info.put("Notice", config.getVideoService());
                isHConfig = (!hospital.getVideoSelfPrice());
                isMustOpen = hospital.getVideoMustOpen();
                isHService = hospital.getVideo();
                break;
            default:
                break;
        }
        Map<String, Object> res = new HashMap<>();
        res.put("isHConfig", isHConfig);
        res.put("isHService", isHService);
        res.put("isMustOpen", isMustOpen);
        res.put("Info", info);
        return res;
    }

    @Override
    public Boolean EditService(long UID, ConfigReq req) {
        Config config = configRepository.findById(UID).orElseThrow(() -> new ApiException(10000, "用户不存在"));
        switch (req.getAType()) {
            case 10:
                config.setNetReferral(req.getService());
                config.setReferralPrice(req.getPrice());
                config.setReferralValid(req.getValid() * 60);
                config.setReferralReception(req.getReception());
                config.setReferralService(req.getNotice());
                break;
            case 11:
                config.setImgText(req.getService());
                config.setImgTextPrice(req.getPrice());
                config.setImgTextValid(req.getValid() * 60);
                config.setImgTextReception(req.getReception());
                config.setImgTextService(req.getNotice());
                break;
            case 12:
                config.setPhone(req.getService());
                config.setPhonePrice(req.getPrice());
                config.setPhoneValid(req.getValid());
                config.setPhoneReception(req.getReception());
                config.setPhoneService(req.getNotice());
                break;
            case 13:
                config.setVideo(req.getService());
                config.setVideoPrice(req.getPrice());
                config.setVideoValid(req.getValid());
                config.setVideoReception(req.getReception());
                config.setVideoService(req.getNotice());
                break;
            default:
                break;
        }
        try {
            configRepository.save(config);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public Map<String, Object> GetPrescription(long UID) {
        DoctorBaseInfo obj = doctorBaseInfoRepository.findByDcId(UID);
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("ZPrescription", obj.getZprescription());
        hashMap.put("XPrescription", obj.getXprescription());
        return hashMap;
    }

    @Override
    public Boolean EditPrescription(long UID, boolean ZPrescription, boolean XPrescription) {
        DoctorBaseInfo obj = doctorBaseInfoRepository.findByDcId(UID);
        obj.setZprescription(ZPrescription);
        obj.setXprescription(XPrescription);
        try {
            doctorBaseInfoRepository.save(obj);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public List<Map<String, Object>> ZRxList(int page, int limit, long UID) {
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;
        List<Map<String, Object>> list = rxOrderMapper.RxList(UID, 0, "1,3", skip, limit);
        if (list != null && list.size() == 0)
            return null;

        List<String> olist = list.stream().filter(m -> m.get("DType").toString().equals("3")).map(e -> e.get("RxOrderNO").toString()).collect(Collectors.toList());
        String RxOrderNOs = "'" + String.join("','", olist) + "'";
        List<Map<String, Object>> drugList = rxOrderMapper.RxDrugList(RxOrderNOs);

        list = list.stream().peek(m -> {
            if (m.get("DType").toString().equals("3"))
                m.put("Drug", drugList.stream().filter(n -> n.get("RxOrderNO").toString().equals(m.get("RxOrderNO").toString()))
                        .peek(x -> {
                            x.put("Suggest", x.get("med_way_nvarchar") + ";" + x.get("freq_nvarchar") + ";" + x.get("day_int") + "天;");
                        })
                        .collect(Collectors.toList()));
        }).collect(Collectors.toList());

        return list;
    }


    @Override
    public List<Map<String, Object>> XRxList(int page, int limit, long UID) {
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;
        List<Map<String, Object>> list = rxOrderMapper.RxList(UID, 0, "2", skip, limit);
        if (list != null && list.size() == 0)
            return null;

        List<String> olist = list.stream().map(e -> e.get("RxOrderNO").toString()).collect(Collectors.toList());
        String RxOrderNOs = "'" + String.join("','", olist) + "'";
        List<Map<String, Object>> drugList = rxOrderMapper.RxDrugList(RxOrderNOs);

        list.forEach(m -> {
            m.put("Drug", drugList.stream().filter(n -> n.get("RxOrderNO").toString().equals(m.get("RxOrderNO").toString()))
                    .collect(Collectors.toList()));
        });

        return list;
    }

    @Override
    public Map<String, Object> CommentList(int page, int limit, long UID, String IsComment, String search) {
        Map<String, Object> result = new HashMap<>();
        int skip = (page - 1) * limit;
        if (skip < 0) skip = 0;
        Boolean comment = null;
        if (IsComment != null && !IsComment.isEmpty() && IsComment.length() > 0)
            comment = Boolean.valueOf(IsComment);
        List<Map<String, Object>> list = commentMapper.CommentList(UID, comment, search, skip, limit);
        long count = commentMapper.countCommentList(UID, comment, search);
        if (list == null || list.size() == 0)
            return null;
        result.put("total", count);
        result.put("list", list);
        return result;
    }

    @Override
    public Map<String, Object> CommentDetail(long UID, String OrderNO) {
        Map<String, Object> obj = commentMapper.CommentDetail(UID, OrderNO);
        obj.put("ReTime", (Boolean) obj.get("IsComment") ? ((Date) obj.get("ReTime")).getTime() : 0);
        return obj;
    }

    @Override
    public Boolean ReComment(String OrderNO, String Re) {
        Comment obj = commentRepository.findById(OrderNO).orElseThrow(() -> new ApiException(10000, "评论不存在"));
        obj.setIsComment(true);
        obj.setRe(Re);
        obj.setReTime(new Date());
        try {
            commentRepository.save(obj);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    @Override
    public Map<String, Object> PcRxList(PcRxListReq req) {
        int skip = (req.getPageNum() - 1) * req.getPageSize();
        if (skip < 0) skip = 0;

        long dcid = userUtils.getUser().getDcId();
        if (req.getBeg() != null && req.getEnd() != null) {
            Calendar ca = Calendar.getInstance();
            ca.setTime(req.getEnd());
            ca.add(Calendar.DAY_OF_MONTH, 1);
            req.setEnd(ca.getTime());
        }
        List<Map<String, Object>> list = rxOrderMapper.PcRxList(dcid, req.getBeg(), req.getEnd(), req.getDType(), req.getChkStatus(), req.getName(), skip, req.getPageSize());
        int count = rxOrderMapper.PcRxCount(dcid, req.getBeg(), req.getEnd(), req.getDType(), req.getChkStatus(), req.getName());
        Map<String, Object> res = new HashMap<>();
        list.forEach(m -> {
            m.put("DTypeName", DType.valueToDesc(((Long) m.get("DType")).intValue()));
            m.put("ChkStatus", ChkStatus.valueToDesc(((Long) m.get("ChkStatus")).intValue()));
            m.put("ChkTime", m.get("ChkTime") == null ? "/" : m.get("ChkTime"));
        });
        res.put("list", list);
        res.put("cnt", count);
        return res;
    }

    /**
     * 添加签名任务
     *
     * @param orderId 订单id
     * @param msspId  用户编号
     * @return 任务id
     */
    @Override
    public Map<String, String> addSignJob(String orderId, String msspId) {
        String xml = rxMainRepository.getXml(orderId);

        long time = System.currentTimeMillis();
        // 获得ca 任务id
        CompletableFuture<String> signJob = CompletableFuture.supplyAsync(() -> {
            return caSendMessage.getSignJob(msspId, xml);
        }, threadPoolExecutor);

        // 获得时间签名任务
        CompletableFuture<String> caTime = CompletableFuture.supplyAsync(() -> {

            String result = caSendMessage.signtss(String.valueOf(time));
            return result;
        }, threadPoolExecutor);

        CompletableFuture<Map<String, String>> result = signJob.thenCombineAsync(caTime, (result1, result2) -> {
            Map<String, String> map = new HashMap<>(MapUtils.getMapInitSize(2));
            JSONObject jsonObject = JSONObject.parseObject(result1);
            if (CaSendMessage.SUCCESS.equals(jsonObject.get(CaSendMessage.MESSAGE))) {
                JSONObject jsonData = JSONObject.parseObject(jsonObject.get("data").toString());
                map.put("signJobId", jsonData.get("signJobId").toString());
            } else {
                throw new ApiException(500, JSONObject.parseObject(result1).get(CaSendMessage.MESSAGE).toString());
            }


            JSONObject timJson = JSONObject.parseObject(result2);
            if (CaSendMessage.SUCCESS.equals(timJson.get(CaSendMessage.MESSAGE))) {
                JSONObject timeJson = JSONObject.parseObject(timJson.get("data").toString());
                redisUtils.set("catime" + orderId + "doctor", String.valueOf(time));

                map.put("timeSignature", timeJson.get("signature").toString());

            } else {
                throw new ApiException(500, JSONObject.parseObject(result2).get(CaSendMessage.MESSAGE).toString());
            }
            return map;
        });

        try {
            return result.get();
        } catch (InterruptedException e) {
            throw new ApiException(400, e.getMessage());
        } catch (ExecutionException e) {
            if ("com.example.common.support.ApiException: err".equals(e.getMessage())) {
                throw new ApiException(400, e.getMessage().split(":")[1]);
            } else {
                throw new ApiException(400, e.getMessage());
            }
        }
    }

    /**
     * 获得当前用户的激活码
     *
     * @param phone 用户的手机号
     * @return 返回用户激活信息
     */
    @Override
    public Map<String, String> getCaMessage(String phone) {
        Map<String, String> map = new HashMap<>(MapUtils.getMapInitSize(3));
        String msspId = rxMainRepository.getCaMessage(phone);

        // 查询用户
        String caResult = caSendMessage.queryUserInfo(msspId);
        JSONObject jsonObject = JSONObject.parseObject(caResult);
        if (CaSendMessage.SUCCESS.equals(jsonObject.get(CaSendMessage.MESSAGE))) {

            String userStatus = JSONObject.parseObject(jsonObject.get("data").toString()).get("userStatus").toString();
            if (CaSendMessage.NOT_ACTIVE.equals(userStatus)) {
                String resultMap = redisUtils.get("ca" + phone + "doctor").toString();
                String[] split = resultMap.split(":");
                map.put("msspId", split[0]);
                map.put("authCode", split[1]);
                // 0 表示未激活
                map.put("userStatus", CaSendMessage.NOT_ACTIVE);
                redisUtils.delete("ca" + phone + "doctor");
            } else if (CaSendMessage.NOT_EXIST.equals(userStatus)) {
                // 用户不存在或者已经促销
                map.put("userStatus", CaSendMessage.NOT_EXIST);

            } else if (CaSendMessage.LOCKED.equals(userStatus)) {
                // 用户被冻结
                map.put("userStatus", CaSendMessage.LOCKED);
            } else if (CaSendMessage.ACTIVE.equals(userStatus)) {
                // 用户已激活
                map.put("msspId", msspId);
                map.put("userStatus", CaSendMessage.ACTIVE);
            }

        }
        return map;
    }

    /**
     * 根据任务id获得任务结果
     *
     * @param signJobId 任务id
     * @param msspId    用户编号
     * @return 返回任务结果
     */
    @Override
    public Map<String, String> querySignJob(String signJobId, String msspId, String orderId) {
        String signJob = caSendMessage.querySignJob(signJobId);
        JSONObject jsonObject = JSONObject.parseObject(signJob);
        Map<String, String> map = new HashMap<>(MapUtils.getMapInitSize(3));
        if (CaSendMessage.SUCCESS.equals(jsonObject.get(CaSendMessage.MESSAGE))) {
            String data = jsonObject.get("data").toString();
            map.putAll(JSONObject.parseObject(data, new TypeReference<Map<String, String>>() {
            }));
            int i = rxMainRepository.updateSigJob(map.get("signCert"), map.get("signResult"), orderId);
            if (i < 0) {
                throw new ApiException(400, "证书保存失败");
            }
        } else {
            throw new ApiException(500, JSONObject.parseObject(signJob).get(CaSendMessage.MESSAGE).toString());

        }
        System.err.println(map);
        return map;
    }

    /**
     * 获取是否签名成功
     *
     * @param plain      原文bash64
     * @param signResult 签名结果
     * @param cert       证书
     * @param orderId    订单id
     * @return 是否签名成功
     */
    @Override
    public Map<String, String> verifySign(String plain, String signResult, String cert, String orderId, String timeSignature) {
        // 拿到时间戳签名的时间
        String timJson = String.valueOf(redisUtils.get("catime" + orderId + "doctor"));
        // 发起参数校验请求
        CompletableFuture<String> verifyResult = CompletableFuture.supplyAsync(() -> {
            return caSendMessage.verifySign(plain, signResult, cert);
        }, threadPoolExecutor);

        // 发起时间校验请求
        CompletableFuture<String> timeResult = CompletableFuture.supplyAsync(() -> {
            return caSendMessage.verifytss(timJson, timeSignature);
        }, threadPoolExecutor);

        // 对任务进行聚合
        CompletableFuture<Map<String, String>> mapCompletableFuture = verifyResult.thenCombineAsync(timeResult, (result1, result2) -> {
            Map<String, String> map = new HashMap<>(MapUtils.getMapInitSize(1));

            if (!CaSendMessage.SUCCESS.equals(JSONObject.parseObject(result2).get(CaSendMessage.MESSAGE).toString())) {
                throw new ApiException(500, JSONObject.parseObject(result2).get(CaSendMessage.MESSAGE).toString());
            }

            if (CaSendMessage.SUCCESS.equals(JSONObject.parseObject(result1).get(CaSendMessage.MESSAGE).toString()) &&
                    CaSendMessage.SUCCESS.equals(JSONObject.parseObject(result2).get(CaSendMessage.MESSAGE).toString())) {
                int i = rxMainRepository.updatVerif(orderId, timeSignature);
                if (i > 0) {
                    map.putAll(JSONObject.parseObject(result1, new TypeReference<Map<String, String>>() {
                    }));
                    redisUtils.delete("catime" + orderId + "doctor");
                    CompletableFuture.runAsync(() -> sendNotice(orderId)); // 给药师发消息
                }
            } else {
                throw new ApiException(500, JSONObject.parseObject(result1).get(CaSendMessage.MESSAGE).toString());
            }

            return map;
        });

        try {
            return mapCompletableFuture.get();
        } catch (InterruptedException e) {
            throw new ApiException(400, e.getMessage());
        } catch (ExecutionException e) {
            if ("com.example.common.support.ApiException: err".equals(e.getMessage())) {
                throw new ApiException(400, e.getMessage().split(":")[1]);
            } else {
                throw new ApiException(400, e.getMessage());
            }
        }
    }
    
    @Value("${drugmappID}")
    private String drugmappID;

    @Value("${drugmappsecret}")
    private String drugmappsecret;

    private void sendNotice(String orderId){
        MsgConfig msgConfig = msgConfigRepository.findById("Pharmacist_Prescription").orElse(null);
        if(msgConfig == null)
            return;        
        String token = wxSendMessage.getAccessToken(drugmappID, drugmappsecret);
        if(token == null)
            return;
        RxMain rxMain = rxMainRepository.findById(orderId).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        OrderMain order = orderMainRepository.findById(rxMain.getOrderNO()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        Pharmacist drug = pharmacistRepository.findById(rxMain.getChkDcId()).orElseThrow(() -> new ApiException(1, "未查询到数据"));
        DoctorBaseInfo doctor = doctorBaseInfoRepository.findByDcId(order.getDcId());
        PatientsInfo patient = patientsInfoRepository.findByOrderNo(rxMain.getOrderNO());
        
        WxSubScribeMessageVo stemp = new WxSubScribeMessageVo();
        stemp.setTouser(drug.getOpenId());
        stemp.setTemplate_id(msgConfig.getTemplateId());
        stemp.setPage("pages/index/index");

        Map<String, WxSubScribeMessageVo.TemplateData> sdata = new HashMap<>();
        sdata.put("thing1", new WxSubScribeMessageVo.TemplateData("您有一个新的待审核处方，请及时处理")); 
        sdata.put("name2", new WxSubScribeMessageVo.TemplateData(doctor.getName()));
        sdata.put("name3", new WxSubScribeMessageVo.TemplateData(patient.getName()));
        sdata.put("thing4", new WxSubScribeMessageVo.TemplateData("处方有效期为7天"));
        stemp.setData(sdata);
        wxSendMessage.sendSubscribeMessage(stemp, token);
    }

}
